package com.qfedu.edu.iotserver.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.edu.bo.Account;
import com.qfedu.edu.bo.SecurityUser;
import com.qfedu.edu.iotserver.mapper.TenantMapper;
import com.qfedu.edu.iotserver.mapper.UserRoleMapper;
import com.qfedu.edu.pojo.Menu;
import com.qfedu.edu.pojo.Role;
import com.qfedu.edu.pojo.Tenant;
import com.qfedu.edu.pojo.User;
import com.qfedu.edu.iotserver.mapper.UserMapper;
import com.qfedu.edu.iotserver.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.edu.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 管理员用户表 服务实现类
 * </p>
 *
 * @author xiaobobo
 * @since 2024-09-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Override
    public UserDetails loadUserByUsername(String loginVoJsonStr) throws UsernameNotFoundException {
        //拿到这个信息之后首先：弄成Java对象
        LoginVo loginVo = JSON.parseObject(loginVoJsonStr, LoginVo.class);
        //取出这个用户名和type
        //前端页面传递的用户名
        String username = loginVo.getUsername();
        Integer type = loginVo.getType();
        if (StringUtils.isEmpty(username) || null == type) {
            throw new UsernameNotFoundException("用户名不对或者type未传递");
        }
        SecurityUser securityUser = new SecurityUser();
        //执行到这里 说明参数是对的
        if (type == 0) {
            return userLogin(username, securityUser,0);
        } else {
            tenantLogin(username, securityUser);
        }
        return securityUser;
    }

    /**
     * 租户的登陆
     * @param username
     * @param securityUser
     */
    private void tenantLogin(String username, SecurityUser securityUser) {
        //说明是会员登陆
        //首先通过用户名去查询这个租户的信息
        QueryWrapper<Tenant> tenantQueryWrapper = new QueryWrapper<>();
        tenantQueryWrapper.eq("name", username);
        Tenant tenant = tenantMapper.selectOne(tenantQueryWrapper);
        if(null==tenant){
            //说明用户名不对
            throw new UsernameNotFoundException("用户名不对");
        }
        //执行到这里 说明用户名是对的 那么就封装参数
        Account account=new Account();
        account.setType(1);
        account.setUsername(tenant.getName());
        account.setPassword(tenant.getPwd());
        account.setId(tenant.getId());
        securityUser.setAccount(account);
        securityUser.setRoleAndPerms(new ArrayList<>());
    }

    /**
     * 管理员的登陆
     * @param username
     * @param securityUser
     * @return
     */
    private SecurityUser userLogin(String username, SecurityUser securityUser,Integer type) {
        //说明是管理员登陆
        //通过用户名查询用户对象
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User userSelect = userMapper.selectOne(userQueryWrapper);
        if (null == userSelect) {
            throw new UsernameNotFoundException("用户名不对");
        }
        roleAndPermHandler(securityUser, userSelect,type);
        return securityUser;
    }

    /**
     * 角色和权限的处理
     * @param securityUser
     * @param userSelect
     */
    private void roleAndPermHandler(SecurityUser securityUser, User userSelect,Integer type) {
        //执行到这里 说明用户名对的
        //通过用户id查询权限  通过用户id查询角色
        List<Role> roleList = userRoleMapper.findRoleByUserId(userSelect.getId());
        List<Menu> menuList = userRoleMapper.findPermdByUserId(userSelect.getId());
        //在这里就需要转换成集合了
        List<String> roleAndPermList = convertListString(roleList, menuList);
        //接下来封装这个返回对象
        Account account = new Account();
        account.setUsername(userSelect.getUserName());
        account.setPassword(userSelect.getPassword());
        account.setId(userSelect.getId());
        account.setType(type);
        //设置权限和角色
        securityUser.setAccount(account);
        securityUser.setRoleAndPerms(roleAndPermList);
    }

    /**
     * 将查询出来的角色和权限转换成List<String>类型的数组
     *
     * @param roleList
     * @param menuList
     * @return
     */
    private List<String> convertListString(List<Role> roleList, List<Menu> menuList) {
        List<String> lists = new ArrayList<>();
        for (int i = 0; i < roleList.size(); i++) {
            lists.add("ROLE_" + roleList.get(i).getName());
        }
        //接下来将权限弄成集合
        for (int i = 0; i < menuList.size(); i++) {
            lists.add(menuList.get(i).getPermVal());
        }
        //最终将这个集合给返回去
        return lists;
    }

}
